import React, { PureComponent, Fragment } from 'react';
import moment from 'moment';
import { connect } from 'dva';
import {
  Button,
  Tag,
  Modal,
  Form,
  message,
  Table,
  Radio,
  Input,
  Icon,
  Drawer,
  Row,
  Switch,
  Progress, DatePicker, Select,Col
} from 'antd';
import MyPagination from '@/components/MyPagination';
import Loading from '@/components/Loading';
import find from 'lodash/find';
import debounce from 'lodash/debounce';
import { ellipsis, afterCloseModal, DescriptionItem } from '@/utils/utils';
import { routerRedux } from 'dva/router';
import BuildModalTitle from '@/components/BuildModalTitle';
import ReactDataGrid from 'react-data-grid';
import mail from './../../images/mail.png'
import mailOpen from './../../images/mail-open.png'
import AddOrEditUser from './addOrEditUser'
import DetailInfo from './Detail'
import AddOrEditStaffs from '../Staffs/AddOrEdit';
import AddOrEditDMAGraph from "./AddOrEditDMAGraph";
import uuid from 'uuid-js';
const FormItem = Form.Item;
const { confirm } = Modal;
const { Option } = Select;

const RadioButton = Radio.Button;

const RadioGroup = Radio.Group;

@connect(({ DMA_analyze, loading,global }) => ({
  DMA_analyze,
  global,
  loading: loading.models.DMA_analyze,
}))
@Form.create()
class BasicList extends PureComponent {
  constructor(props) {
    super(props);
    this.permissions = JSON.parse(sessionStorage.getItem('permissions'));
    this.state = {
      showAddBtn: find(this.permissions, { name: 'device_add_and_edit' }),
      showdelBtn: find(this.permissions, { name: 'device_delete' }),
      showPasswordBtn: find(this.permissions, { name: 'user_default_password_edit' }),
      user_password_reset: find(this.permissions, { name: 'user_password_reset' }),
      visible: false,
      done: false,
      page: 1,
      per_page: 30,
      username: '',
      editRecord: {},
      selectedRowKeys: [],
      uuid: uuid.create(),
      showType:"2"
    };
  }


  componentDidMount() {

    const { dispatch } = this.props;
    const {
      DMA_analyze: { pageLoaded, scrollData },
    } = this.props;
    console.log('pageLoaded', pageLoaded);
    const table = document.querySelector('.ant-table-body');
    if (pageLoaded) {
      setTimeout(() => {
        table.scrollTop = scrollData.y;
        table.scrollLeft = scrollData.x;
      }, 0);

    } else {
      const {
        DMA_analyze: { searchParams },
      } = this.props;
      console.log('searchParams', searchParams);
      dispatch({
        type: 'DMA_analyze/fetch',
        payload: searchParams,
        callback: () => {
          const { dispatch } = this.props;
          dispatch({
            type: 'DMA_analyze/changeLoaded',
          });
          dispatch({
            type: 'DMA_analyze/changeTableY',
          });
        },
      });

    }
    window.addEventListener('resize', this.resize);
    table.addEventListener('scroll', debounce(this.scroll, 150));
  }

  scroll = (e) => {
    console.log('scroll');
    const { dispatch } = this.props;
    dispatch({
      type: 'DMA_analyze/changeScroll',
      payload: {
        x: e.target.scrollLeft,
        y: e.target.scrollTop,
      },
    });
  };

  resize = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'DMA_analyze/changeTableY',
    });
  };
  findChildFunc = (cb)=> {
    this.file=cb
  }

  componentWillUnmount() {
    console.log('componentWillUnmount');
    window.removeEventListener('resize', this.resize);
    const table = document.querySelector('.ant-table-body');
    table.removeEventListener('scroll', debounce(this.scroll, 300));
  }

  handleSearch = (values, cb) => {
    console.log('handleSearch', values);
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: 'DMA_analyze/fetch',
      payload: {
        ...values,
      },
      callback() {
        console.log('handleSearch callback');
        if (cb) cb();
      },
    });
  };

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
      DMA_analyze: { searchParams },
    } = this.props;
    return (
      <Form layout="inline" className="search-form">
        <FormItem>
          <FormItem label={'开始日期'}>
            {getFieldDecorator('start_date', {
              initialValue: searchParams.start_date ? moment(searchParams.start_date) : '',
            })(
              <DatePicker
                style={{width: '120px'}}
                format="YYYY-MM-DD"
              />,
            )}
          </FormItem>
          <FormItem label={'结束日期'}>
            {getFieldDecorator('end_date', {
              initialValue: searchParams.end_date ? moment(searchParams.end_date) : '',
            })(
              <DatePicker
                style={{width: '120px'}}
                format="YYYY-MM-DD"
              />,
            )}
          </FormItem>
          <Button
            type="primary"
            icon='search'
            onClick={() => {
              const { form } = this.props;
              form.validateFields((err, fieldsValue) => {
                if (err) return;

                this.handleSearch({
                  start_date: fieldsValue.start_date ? moment(fieldsValue.start_date).format('YYYY-MM-DD') : '',
                  end_date: fieldsValue.end_date ? moment(fieldsValue.end_date).format('YYYY-MM-DD') : '',
                });

              });
            }}
          >
            查询
          </Button>
          <Button style={{ marginLeft: 8 }} icon='redo' onClick={this.handleFormReset}>
            重置
          </Button>


        </FormItem>

      </Form>
    );
  }

  handleAdd = () => {
    const formValues = this.AddForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    const that = this;
    this.props.dispatch({
      type: 'DMA_analyze/add',
      payload: {
        ...formValues,
        parent_id:formValues.parent_id?formValues.parent_id.split('$')[0]:'',
      },
      callback() {
        message.success('添加小区成功');
        that.setState({
          addModal: false,
        });
        const {
          DMA_analyze: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };

  handleFormReset = () => {
    const { form } = this.props;
    form.resetFields();
    this.handleSearch({
      start_date: moment(new Date().getFullYear() + '-' + (parseInt(new Date().getMonth()) + 1) + '-' + '01', "YYYY-MM-DD").format("YYYY-MM-DD"),
      end_date: moment(new Date()).format('YYYY-MM-DD'),
    });
  };

  handleEdit = () => {
    const formValues = this.EditForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    const that = this;
    this.props.dispatch({
      type: `DMA_analyze/edit`,
      payload: {
        ...formValues,
        parent_id:formValues.parent_id?formValues.parent_id.split('$')[0]:'',
        id: this.state.editRecord.id,
      },
      callback() {
        message.success('修改小区成功');
        that.setState({
          editModal: false,
        });
        const {
          DMA_analyze: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };
  handleDelete = id => {
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: `DMA_analyze/remove`,
      payload: { id },
      callback: () => {
        message.success('删除小区成功');
        const {
          DMA_analyze: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };
  render() {
    const that = this;
    const {
      DMA_analyze: { data, loading, tableY, meta, searchParams, selectedRowKeys },
      global:{gridTableW}
    } = this.props;

    const defaultColumnProperties = {
      resizable: true,
    };
    const columns = [
      {
        title: '名称',
        dataIndex: 'name',
        key: 'name',
        width: '160px'
      },
      {
        title: '是否存在图关系',
        dataIndex: 'graph',
        key: 'graph',
        width: '140px',
        render: (val, record, index) => {
          return  <Fragment>
            {
              record.graph.edges.length>0?<p className="table-success table-status">存在</p>:<p className="table-error table-status">不存在</p>
            }
          </Fragment>
            }
      },
      {
        title: '备注',
        dataIndex: 'remark',
        key: 'remark',

      },
      {
        title: '操作',
        key: 'operate',
        classname:'operate',
        width: '140px',
        render: (val, record, index) => {
        return  <Fragment>
          <Button
            type="primary"
            size="small"
            icon="branches"
            onClick={(e) => {
              this.setState({
                uuid: uuid.create(),
                editRecord:record,
                graphModal2: false,
              },function (){
                this.setState({
                  graphModal2: true,
                })
              });
            }
            }
          >查看漏损关系
          </Button>

        </Fragment>
        }
      }

    ]


    let totalWidth = 0;
    for (let i = 0; i < columns.length; i++) {
      totalWidth += columns[i].width;
    }
    if (totalWidth < gridTableW) {
      columns[columns.length - 1].width = columns[columns.length - 1].width + gridTableW - totalWidth;
    }

    return <div className="custom-card">
      <div className="table-title"><span className={'title-item'}>漏损分析</span>
      </div>
      <div className="table-page">
        <Row>
          <div className="table-condition">{this.renderSimpleForm()}</div>
          <div style={{display:'flex'}}>
            <div style={{width:'550px'}}>
              <div className={'table-data-content'}>
                <Table
                  className='meter-table ant-table-interval'
                  loading={loading}
                  rowKey={record => record.id}
                  dataSource={data}
                  columns={columns}
                  scroll={{y: tableY}}
                  bordered
                  pagination={false}
                  size="small"
                />
                {
                  loading&&<Loading />
                }
              </div>
            </div>
            <div style={{flex:1,background:'#ccc',height:tableY,position:'relative'}}  key={this.state.uuid}>
              {
                this.state.editRecord.name&&
                <h2 style={{position:'absolute',left:'16px',top:'8px',zIndex:99,color:'blue'}}>“{this.state.editRecord.name}“图关系</h2>
              }
              {
                this.state.editRecord.name&&
                <div style={{position:'absolute',left:'16px',top:'44px',zIndex:99,color:'blue'}}>
                  <Select  style={{ width: 150 }} value={this.state.showType} onChange={(e)=>{
                    this.setState({
                      showType:e,
                      uuid: uuid.create(),
                      graphModal2: false,
                    },function (){
                      this.setState({
                        graphModal2: true,
                      })
                    })
                  }}>
                    <Option value="1">只显示灰色线</Option>
                    <Option value="2">只显示蓝色线</Option>
                    <Option value="0">全部显示</Option>
                  </Select>
                </div>

              }
              {
                this.state.graphModal2&&
                <AddOrEditDMAGraph
                  showType={this.state.showType}
                  onClose={() => {
                    this.setState({
                      graphModal: false,
                      editRecord: {},
                    });
                  }}
                  editRecord={this.state.editRecord}
                  onSave={this.handleAdd}
                  handleSearch={()=>{
                    this.handleSearch(searchParams)
                  }}
                  cancel={()=>{
                    this.setState({
                      graphModal: false,
                      editRecord: {},
                    });
                  }}
                  wrappedComponentRef={(inst) => this.AddForm = inst}
                />
              }
              {
                this.state.editRecord.name&&
                <div style={{position:'absolute',right:'16px',bottom:'8px',zIndex:99,color:'blue'}}>
                  <Button type={'primary'} onClick={()=>{
                    this.setState({
                      graphModal: true,
                    })
                  }}>全屏</Button>
                </div>
              }
            </div>
          </div>
        </Row>



      </div>
      <Modal
        title={<BuildModalTitle visible={this.state.addModal} modalClass="addModal" title="添加DMA分区"/>}
        className="addModal"
        visible={this.state.addModal}
        centered
        destroyOnClose
        width={600}
        afterClose={() => {
          afterCloseModal(); // destroyOnClose需要
        }}
        onCancel={()=> {
          this.setState({addModal: false})
        }}
        onOk={this.handleAdd}
      >
        <AddOrEditUser
          wrappedComponentRef={(inst) => this.AddForm = inst}/>

      </Modal>
      <Modal
        title={<BuildModalTitle visible={this.state.editModal} modalClass="editModal"
                                title={`修改 ${this.state.editRecord.name}`}/>}
        destroyOnClose
        visible={this.state.editModal}
        centered
        className="editModal"
        width={600}
        afterClose={() => {
          afterCloseModal(); // destroyOnClose需要
        }}
        onCancel={() => {
          this.setState({ editModal: false, editRecord: {} });
        }}
        onOk={this.handleEdit}
      >
        <AddOrEditUser
          editRecord={this.state.editRecord}
          wrappedComponentRef={(inst) => this.EditForm = inst}/>
      </Modal>
      <Drawer
        title={`”${this.state.editRecord.name}“图关系`}
        placement="right"
        destroyOnClose
        onClose={() => {
          this.setState({
            graphModal: false,
            editRecord: {},
          });
        }}
        width={'100vw'}
        visible={this.state.graphModal}
      >
        <AddOrEditDMAGraph
          type={'modal'}
          onClose={() => {
            this.setState({
              graphModal: false,
              editRecord: {},
            });
          }}
          editRecord={this.state.editRecord}
          onSave={this.handleAdd}
          handleSearch={()=>{
            this.handleSearch(searchParams)
          }}
          cancel={()=>{
            this.setState({
              graphModal: false,
              editRecord: {},
            });
          }}
          wrappedComponentRef={(inst) => this.AddForm = inst}
        />
      </Drawer>
    </div>;
  }
}

export default BasicList;
